﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.ComponentModel;
using EIA.PM.Model;
using EIA.Basic.Model;
using System.Collections.ObjectModel;

namespace EIA.SLClient.PlatManage.PMMgr
{
    public class SR_RoleListViewModel : SimpleMvvmToolkit.ViewModelBase<SR_RoleListViewModel>
    {
        public SR_RoleListViewModel()
        {
            this.RegisterToReceiveMessages<IList<TStaff>>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.SR_STAFFS_SELECTED, EP_StaffsSelected);
        }

        private void EP_StaffsSelected(object sender, SimpleMvvmToolkit.NotificationEventArgs<IList<TStaff>> e)
        {
            SelectedStaffs = e.Data;
            SelectRoles();
        }

        private void Busy(string msg = "等待...")
        {
            IsBusy = true;
            SendMessage<bool>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.SR_BUSY_STATE, new SimpleMvvmToolkit.NotificationEventArgs<bool>(msg, true));
        }

        private void Free()
        {
            IsBusy = false;
            SendMessage<bool>(EIA.SLClient.PlatManage.Infrastructure.MessageTokens.SR_BUSY_STATE, new SimpleMvvmToolkit.NotificationEventArgs<bool>("", false));
        }

        #region notifyprop

        protected bool _IsBusy;
        /// <summary>
        /// 
        /// </summary>
        public bool IsBusy
        {
            get { return _IsBusy; }
            set
            {
                _IsBusy = value;
                NotifyPropertyChanged(m => m.IsBusy);
            }
        }

        protected PagedCollectionView _RoleCollection;
        /// <summary>
        /// 注释
        /// </summary>
        public PagedCollectionView RoleCollection
        {
            get { return _RoleCollection; }
            set
            {
                _RoleCollection = value;
                NotifyPropertyChanged(m => m.RoleCollection);
            }
        }

        protected IList<TStaff> _SelectedStaffs;
        /// <summary>
        /// 注释
        /// </summary>
        public IList<TStaff> SelectedStaffs
        {
            get { return _SelectedStaffs; }
            set
            {
                _SelectedStaffs = value;
                NotifyPropertyChanged(m => m.SelectedStaffs);
            }
        }


        #endregion

        #region command

        #region RetrieveItemsCommand

        private SimpleMvvmToolkit.DelegateCommand _RetrieveItemsCommand = null;
        public SimpleMvvmToolkit.DelegateCommand RetrieveItemsCommand
        {
            get
            {
                if (_RetrieveItemsCommand == null)
                {
                    _RetrieveItemsCommand = new SimpleMvvmToolkit.DelegateCommand(RetrieveItems, CanExcuteRetrieveItems);
                } return _RetrieveItemsCommand;
            }
            set { _RetrieveItemsCommand = value; NotifyPropertyChanged(m => m.RetrieveItemsCommand); }
        }

        public void RetrieveItems()
        {
            EIA.PM.BLL.ClientProxy.TRoleProxy proxy = new EIA.PM.BLL.ClientProxy.TRoleProxy();
            Busy();
            proxy.ListAll((lst) =>
            {
                Free();
                CompositeIsChecked[] checks = new CompositeIsChecked[lst.Count];
                for (int i = 0; i < lst.Count; i++)
                {
                    checks[i] = new CompositeIsChecked();
                    checks[i].IsChecked = false;
                }
                RoleCollection = new PagedCollectionView(new ObservableCollection<Tuple<TRole, CompositeIsChecked>>(lst.Zip(checks, (r, c) => { return new Tuple<TRole, CompositeIsChecked>(r, c); })));
                SelectRoles();
            }, (ex) =>
            {
                Free();
                System.Windows.MessageBox.Show("获取角色列表发生错误！", "提示", System.Windows.MessageBoxButton.OK);
            });
        }

        public bool CanExcuteRetrieveItems()
        {
            return true;
        }

        #endregion

        #region SaveCommand

        private SimpleMvvmToolkit.DelegateCommand _SaveCommand = null;
        public SimpleMvvmToolkit.DelegateCommand SaveCommand
        {
            get
            {
                if (_SaveCommand == null)
                {
                    _SaveCommand = new SimpleMvvmToolkit.DelegateCommand(Save, CanExcuteSave);
                } return _SaveCommand;
            }
            set { _SaveCommand = value; NotifyPropertyChanged(m => m.SaveCommand); }
        }

        public void Save()
        {
            if (SelectedStaffs == null || SelectedStaffs.Count == 0) return;
            EIA.PM.BLL.ClientProxy.XStaffRolesProxy proxy = new PM.BLL.ClientProxy.XStaffRolesProxy();
            Busy("更新用户角色");
            List<int> stf_ids = new List<int>();
            List<int> role_ids = new List<int>();
            foreach (TStaff stf in SelectedStaffs)
            {
                stf_ids.Add(stf.StfId);
            }
            foreach (Tuple<TRole, CompositeIsChecked> rc in RoleCollection)
            {
                if (rc.Item2.IsChecked) role_ids.Add(rc.Item1.RoleId);
            }
            proxy.UpdateMany(stf_ids, role_ids, (r) =>
            {
                Free();
                if (!r)
                {
                    System.Windows.MessageBox.Show("角色更新失败！", "提示", System.Windows.MessageBoxButton.OK);
                }

            }, (ex) =>
            {
                Free();
                System.Windows.MessageBox.Show("角色更新发生错误！", "提示", System.Windows.MessageBoxButton.OK);
            });
        }

        public bool CanExcuteSave()
        {
            return true;
        }

        #endregion

        #endregion

        public void OnLoad()
        {
            if (RoleCollection == null) RetrieveItems();
        }

        /// 更新角色选择列表
        private void SelectRoles()
        {
            if (RoleCollection == null) return;
            if (SelectedStaffs == null)
            {
                foreach (Tuple<TRole, CompositeIsChecked> r in RoleCollection)
                {
                    r.Item2.IsChecked = false;
                }
            }
            else if (SelectedStaffs.Count == 1)
            {
                int staff_id = SelectedStaffs[0].StfId;
                EIA.PM.BLL.ClientProxy.XStaffRolesProxy proxy = new PM.BLL.ClientProxy.XStaffRolesProxy();
                Busy("刷新角色，等待...");
                proxy.List(staff_id, (roles) =>
                {
                    Free();
                    foreach (Tuple<TRole, CompositeIsChecked> rolecheck in RoleCollection)
                    {
                        if (roles.Item2.Contains(rolecheck.Item1.RoleId))
                        {
                            rolecheck.Item2.IsChecked = true;
                        }
                        else
                        {
                            rolecheck.Item2.IsChecked = false;
                        }
                    }

                }, (ex) =>
                {
                    Free();
                    System.Windows.MessageBox.Show("获取用户角色失败！", "提示", System.Windows.MessageBoxButton.OK);
                });
            }
            else // multi staffs clear selected roles
            {
                foreach (Tuple<TRole, CompositeIsChecked> r in RoleCollection)
                {
                    r.Item2.IsChecked = false;
                }
            }
        }
    }
    public class CompositeIsChecked : SimpleMvvmToolkit.ModelBase<CompositeIsChecked>
    {

        protected bool _IsChecked;
        /// <summary>
        /// 注释
        /// </summary>
        public bool IsChecked
        {
            get { return _IsChecked; }
            set
            {
                _IsChecked = value;
                NotifyPropertyChanged(m => m.IsChecked);
            }
        }
    }
}